<template>
	<div>
		<el-form inline :model="query" label-width="80px">
			<el-form-item label="试卷名称">
				<el-input v-model="query.name" class="width260 margin-right10" placeholder="请输入关键字"></el-input>
			</el-form-item>
			<el-form-item label="地区分类">
				<el-cascader :props="props" v-model="query.city" :options="areaData" placeholder="请选择地区"
					class="width260 margin-right10"></el-cascader>
			</el-form-item>
			<el-form-item label="状态">
				<el-select placeholder="请选择状态" v-model="query.status" class="width260 margin-right10">
					<el-option label="待发布" :value="0"></el-option>
					<el-option label="审核中" :value="1"></el-option>
					<el-option label="已发布" :value="2"></el-option>
					<el-option label="未通过" :value="3"></el-option>
				</el-select>
			</el-form-item>
			<el-button type="primary" icon="el-icon-search" class="margin-left10" @click="handleSearch">搜索</el-button>
			<el-button type="default" icon="el-icon-refresh-right" @click="handleRefresh">重置</el-button>
			<el-button type="text" @click="clickSort(1)">按添加顺序排序</el-button>
			<el-button type="text" @click="clickSort(2)">按序号排序</el-button>
		</el-form>
		<div class="margin-top20 margin-bottom20 row-me row-center">
			<template v-if="roleType==3">
				<el-button type="primary" @click="handleAdd">添加试卷</el-button>
				<el-button type="primary" @click="handleBatchDel">批量删除</el-button>
				<el-button type="warning" @click="clickRenew" v-if="roleType==3">一键更新</el-button>
			</template>
			<template v-else>
				<el-button type="primary" @click="handleAdd" v-if="page=='famousQuestion'">从题库系统添加</el-button>
				<el-button type="primary" @click="handleAdd" v-if="page=='historicalQuestion'">新建真题</el-button>
				<el-button type="primary" @click="handleAdd" v-if="page=='modelMatch'">从题库添加</el-button>
				<el-button type="primary" @click="handleBatchDel">批量删除</el-button>
			</template>
			<div class="flex1"></div>
			<el-button type="text" @click="modelVisible=true" v-if="page=='modelMatch'">首页模考大赛配置</el-button>
			<el-button type="text" @click="typeVisible=true" v-if="roleType==3&&page=='historicalQuestion'">试卷分类管理</el-button>
		</div>
		<el-table :data="tableData" ref="el_table" border class="margin-top20" header-cell-class-name="table-header-style"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center"></el-table-column>
			<el-table-column type="index" width="80" align="center" label="排序"></el-table-column>
			<el-table-column prop="id" label="试卷ID" width="80" align="center"></el-table-column>
			<el-table-column show-overflow-tooltip label="模考大赛名称" align="center" width="300" v-if="page=='modelMatch'">
				<template slot-scope="scope">
					<div class="line1">{{scope.row.mockName}}</div>
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip label="试卷" width="500" v-if="page!='modelMatch'">
				<template slot-scope="scope">
					<div class="line1">{{scope.row.name}}</div>
				</template>
			</el-table-column>
			<el-table-column prop="sourceName" label="试卷简称" align="center" v-if="page=='historicalQuestion'"
				width="120"></el-table-column>
			<el-table-column prop="questionCount" label="题目数量" width="100" align="center">
				<template slot-scope="scope">
					<div v-if="page=='modelMatch'">{{scope.row.examPaper?scope.row.examPaper.questionCount:''}}</div>
					<div v-else>{{scope.row.questionCount}}</div>
				</template>
			</el-table-column>
			<el-table-column label="考试时间" width="200" align="center" v-if="page=='modelMatch'">
				<template slot-scope="{row}">
					<span v-if="row.examStart&&row.examEnd">{{row.examStart}}-{{row.examEnd}}</span>
				</template>
			</el-table-column>
			<el-table-column prop="totalScore" label="分值" width="100" align="center">
				<template slot-scope="scope">
					<div v-if="page=='modelMatch'">{{scope.row.examPaper?scope.row.examPaper.totalScore:''}}</div>
					<div v-else>{{scope.row.totalScore}}</div>
				</template>
			</el-table-column>
			<el-table-column prop="peopleNum" label="参与人数" width="100" align="center"
				v-if="page=='modelMatch'"></el-table-column>
			<el-table-column prop="provinces" label="地区" align="center">
				<template slot-scope="scope">
					<div class="row-me">
						<el-tag v-if="scope.row.province==0">默认</el-tag>
						<el-tag class="margin-right5"
							v-else-if="scope.row.provinceName&&scope.row.province!=0&&($.isEmpty(scope.row.cityName)||scope.row.city==0)">{{scope.row.provinceName}}</el-tag>
						<el-tag v-if="scope.row.cityName&&scope.row.city!=0">{{scope.row.cityName}}</el-tag>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="questionCount" label="权限设置" width="100" align="center" v-if="page=='famousQuestion'">
				<template slot-scope="{row}">
					<span v-if="row.buyType==1">无权限</span>
					<span v-else-if="row.buyType==2">需分享</span>
					<span v-else-if="row.buyType==3">需授权</span>
				</template>
			</el-table-column>
			<el-table-column prop="virtualPeople" label="二维码" width="120" align="center">
				<template slot-scope="scope">
					<el-button type="text" @click="lookQrcode(scope.row)"> 点击查看</el-button>
				</template>
			</el-table-column>
			<el-table-column label="状态" width="100" v-if="page=='modelMatch'">
				<template slot-scope="scope">{{ scope.row.status | testStatus }}</template>
			</el-table-column>
			<el-table-column label="状态" width="100" v-if="page!='modelMatch'">
				<template slot-scope="scope">{{ scope.row.status | testPaperStatus }}</template>
			</el-table-column>
			<el-table-column label="操作" align="center" width="320" fixed="right">
				<template slot-scope="scope">
					<el-button
						v-if="(!scope.row.mockStatus&&page=='modelMatch')||((!scope.row.status || scope.row.status == 3)&&page!='modelMatch')"
						type="text" icon="el-icon-s-promotion" style="color:#67C23A"
						@click="releaseHandle(scope.$index, scope.row, 1)">发布
					</el-button>
					<el-button v-else-if="(scope.row.mockStatus == 1&&page=='modelMatch')||scope.row.status == 2" type="text"
						icon="el-icon-download" style="color:#E6A23C" @click="releaseHandle(scope.$index, scope.row, 0)">撤销
					</el-button>
					<el-button v-else-if="scope.row.status == 1" type="text">
						<el-dropdown style="color:#67C23A;font-size:12px" size="medium" @command="verifyHandle($event, scope.row)">
							<span class="el-dropdown-link"> <i class="el-icon-s-check"></i> 审核 </span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="2">通过</el-dropdown-item>
								<el-dropdown-item command="3">不通过</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</el-button>
					<el-button type="text" v-if="page!='modelMatch'||roleType==3"
						@click="handleAddUser(scope.row)">授权用户</el-button>
					<el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
					<el-button type="text" @click="updateItemCopy(scope.row)">复制</el-button>
					<el-button type="text" @click="handleAdd(scope.row)">编辑</el-button>
					<el-popconfirm title="确认删除？" @confirm="handleDel(scope.row.id)">
						<el-button slot="reference" type="text">删除</el-button>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<div class="margin-top10">
			<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="query.pageNumber"
				:page-sizes="[30, 40, 50, 60]" @size-change="handleSizeChange" :page-size="query.pageSize" :total="pageTotal"
				@current-change="handlePageChange"></el-pagination>
		</div>

		<!-- 新增编辑分类 -->
		<el-dialog title="试卷分类管理" :visible.sync="typeVisible" width="40%" @close="getTypeData">
			<el-table :data="typeTableData" border>
				<el-table-column label="分类名称" align="center">
					<template slot-scope="{row}">
						<el-input v-model="row.name" v-if="row.isEdit"></el-input>
						<span v-else>{{row.name}}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" width="200">
					<template slot-scope="scope">
						<el-button type="text" v-if="scope.row.isEdit" @click="handleTypeAdd(scope.row)">保存</el-button>
						<el-button type="text" @click="$set(scope.row,'isEdit',true)" v-else>编辑</el-button>
						<el-popconfirm title="确认删除？" @confirm="handleTypeDel(scope.row.id)">
							<el-button slot="reference" type="text">删除</el-button>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<div class="margin-top10">
				<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="typeQuery.pageNumber"
					:page-sizes="[10, 20, 30, 40]" @size-change="handleSizeTypeChange" :page-size="typeQuery.pageSize"
					:total="pageTypeTotal" @current-change="handlePageTypeChange"></el-pagination>
			</div>
			<div class="margin-top20 row-me center-all">
				<el-input v-model="typeQuery.name" placeholder="请输入分类名称" class="margin-right20 width300"></el-input>
				<el-button type="primary" @click="handleTypeAdd">新增</el-button>
			</div>
			<span slot="footer">
				<el-button type="primary" @click="typeVisible = false">关 闭</el-button>
			</span>
		</el-dialog>
		<!-- 二维码弹框 -->
		<el-dialog title="二维码" :visible.sync="qrcodeVisible" width="40%">
			<div class="column-me center-all font-size14">
				<div class="row-me">
					<div class="shijuan">
						试卷二维码 ：
					</div>
					<div>
						<div class="row-me flex-end2">
							<div id="qrCode">
								<div id="code" ref="appExamQrCodeUrl" title="" align="center" class="margin-top10 ">
								</div>
							</div>
							<span class="margin-left10 pointer" @click="handleDownloadAppExamQrIMg('code')"> <i
									class="el-icon-download"></i>点击下载二维码</span>
						</div>
					</div>
				</div>
				<div class="row-me margin-top20">
					<div class="shijuan">
						答案二维码 ：
					</div>
					<div>
						<div class="row-me flex-end2">
							<div id="qrCode">
								<div id="code2" ref="appExamQrCodeUrl2" title="" align="center" class="margin-top10 ">
								</div>
							</div>
							<span class="margin-left10 pointer" @click="handleDownloadAppExamQrIMg('code2')"> <i
									class="el-icon-download"></i>点击下载二维码</span>
						</div>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="qrcodeVisible = false">关闭</el-button>
			</span>
		</el-dialog>

		<!-- 历年真题从题库添加 -->
		<el-dialog title="选择试卷" :visible.sync="historyVisible" width="60%">
			<div class="row-me row-center margin-bottom20">
				<el-input class="width260 margin-right20" v-model="historyQuery.name" placeholder="请输入试卷名称"></el-input>
				<el-button type="text" @click="historySearch">搜索</el-button>
				<el-button type="text" @click="historyRefresh">重置</el-button>
			</div>
			<el-table :data="historyTableData" border header-cell-class-name="table-header-style"
				@selection-change="handleHistorySelectionChange">
				<el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column type="index" width="80" align="center" label="序号"></el-table-column>
				<el-table-column show-overflow-tooltip label="试卷名称" align="center">
					<template slot-scope="scope">
						<div class="line1">{{scope.row.name}}</div>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="试卷简称" align="center"></el-table-column>
				<el-table-column prop="provinces" label="发布地区" align="center">
					<template slot-scope="scope">
						<div class="row-me">
							<span>{{scope.row.provinces}}</span>
							<span>{{scope.row.cityName}}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="questionCount" label="题目数量" width="100" align="center"></el-table-column>
			</el-table>
			<div class="margin-top10">
				<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="historyQuery.pageNumber"
					:page-size="historyQuery.pageSize" :total="historyPageTotal"
					@current-change="handleHistoryPageChange"></el-pagination>
			</div>
			<span slot="footer">
				<el-button @click="historyVisible=false">取 消</el-button>
				<el-button type="primary" @click="handleHistorySave">确认添加</el-button>
			</span>
		</el-dialog>

		<!-- 首页模考大赛配置 -->
		<el-dialog title="首页模考大赛配置" :visible.sync="modelVisible" width="60%">
			<div class="row-me row-center margin-bottom20">
				<el-cascader :props="modelProps" v-model="modelQuery.area" :options="areaData" placeholder="请选择地区"
					class="width260 margin-right20" @change="onModelareaChange"></el-cascader>
				<el-button type="primary" @click="modelSearch">搜索</el-button>
				<div class="flex1"></div>
				<el-button type="primary" @click="handleConfigEdit">新建</el-button>
			</div>
			<el-table :data="modelTableData" border header-cell-class-name="table-header-style">
				<el-table-column type="index" width="80" align="center" label="序号"></el-table-column>
				<el-table-column width="80" align="center" label="状态">
					<template slot-scope="scope">
						<span>{{scope.row.configStatus?'开启':'关闭'}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="provinces" label="地区" align="center">
					<template slot-scope="scope">
						<div class="row-me">
							<span>{{scope.row.provinceName}}</span>
							<span>{{scope.row.cityName}}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="labelName" label="模考大赛标签" align="center"></el-table-column>
				<el-table-column show-overflow-tooltip label="关联试卷名称" align="center">
					<template slot-scope="scope">
						<div class="line1">{{scope.row.mockName}}</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" align="center">
					<template slot-scope="scope">
						<el-button type="text" @click="handleConfigEdit(scope.row)">编辑</el-button>
						<el-button type="text" @click="handleConfigDel(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="margin-top10">
				<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="modelQuery.pageNumber"
					:page-size="modelQuery.pageSize" :total="modelPageTotal"
					@current-change="handleModelPageChange"></el-pagination>
			</div>
			<span slot="footer">
				<el-button @click="modelVisible=false">关 闭</el-button>
			</span>
		</el-dialog>

		<!-- 新建 -->
		<el-dialog :title="modelForm.id?'编辑':'新建'" :visible.sync="modelAddVisible" width="600px">
			<el-form :model="modelForm" label-width="120px" :rules="modelRules" ref="modelForm">
				<el-form-item label="选择地区" required>
					<el-cascader :props="modelProps" v-model="modelForm.area" :options="areaData" placeholder="请选择地区"
						class="width260" @change="onModelChange"></el-cascader>
				</el-form-item>
				<el-form-item label="模考大赛标签" prop="labelName">
					<el-select v-model="modelForm.labelName" multiple filterable allow-create default-first-option
						placeholder="请选择模考大赛标签" class="width260"></el-select>
				</el-form-item>
				<el-form-item label="选择试卷" prop="mockId">
					<el-select v-model="modelForm.mockId" placeholder="请选择试卷" class="width260">
						<el-option v-for="item in modelList" :key="item.id" :label="item.mockName" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="显示状态" prop="configStatus">
					<el-radio-group v-model="modelForm.configStatus">
						<el-radio :label="0">关闭</el-radio>
						<el-radio :label="1">永久开启</el-radio>
						<el-radio :label="2">时间段开启</el-radio>
					</el-radio-group>
					<el-date-picker v-if="modelForm.configStatus==2" v-model="configDate" type="datetimerange" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
						@change="configDateChange">
					</el-date-picker>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="modelAddVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleModelSave">确定</el-button>
			</span>
		</el-dialog>

		<!-- 新建 -->
		<el-dialog :title="form.id?'编辑模考':'新建模考'" :visible.sync="mockExamVisible" width="60%" :modal-append-to-body="false"
			append-to-body>
			<el-form :model="form" label-width="120px" :rules="mockExamRules" ref="form">
				<el-form-item label="大赛名称" prop="mockName">
					<el-input v-model="form.mockName" placeholder="请输入大赛名称"></el-input>
				</el-form-item>
				<el-form-item label="标签管理" prop="labelId">
					<!-- 	<el-select v-model="form.labelId" placeholder="请选择模考大赛标签" clearable multiple class="width100Per">
						<el-option :label="item.name" v-for="item in tagList" :key="item.id" :value="item.id+''"></el-option>
					</el-select> -->
					<el-select v-model="form.labelName" multiple filterable allow-create default-first-option
						placeholder="请选择模考大赛标签" @change="$forceUpdate()"></el-select>
				</el-form-item>
				<div class="row-me flex-wrap">
					<el-form-item label="大赛地区" prop="area">
						<el-cascader :props="{value: 'id',label: 'name',checkStrictly: true,multiple: true}" v-model="form.area"
							:options="areaData" placeholder="请选择地区" class="width260" @change="onMocklChange"></el-cascader>
					</el-form-item>
					<el-form-item label="考试时间" prop="examStart">
						<el-date-picker v-model="examDate" type="datetimerange" range-separator="至" start-placeholder="开始日期"
							end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" @change="mockDateChange">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="报名时间" prop="applyStart">
						<el-date-picker v-model="applyDate" type="datetimerange" range-separator="至" start-placeholder="开始日期"
							end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" @change="applyDateChange">
						</el-date-picker>
					</el-form-item>
				</div>
				<div class="row-me flex-wrap">
					<el-form-item label="虚拟人数">
						<div class="row-me row-center">
							<el-input placeholder="请输入虚拟人数" type="number" v-model="form.virtCount"
								class="width200 margin-right20"></el-input>
						</div>
					</el-form-item>
					<el-switch v-model="form.isAdd" class="margin-right20 line-height40"></el-switch>
					<el-form-item label="自增设置" v-if="form.isAdd">
						<div class="row-me row-center">
							<el-input class="width100" v-model="form.addStart" placeholder="请输入"></el-input>
							<span class="margin-left5 margin-right5">~</span>
							<el-input class="width100" v-model="form.addEnd" placeholder="请输入"></el-input>
							<el-select placeholder="请选择" v-model="form.addTime" class="margin-left20">
								<el-option label="每30分钟" :value="1"></el-option>
								<el-option label="每小时" :value="2"></el-option>
								<el-option label="每天" :value="3"></el-option>
							</el-select>
						</div>
					</el-form-item>
				</div>
				<el-form-item label="大赛说明" prop="mockComment">
					<div class="row-me">
						<vue-ueditor-wrap v-model="form.mockComment" editor-id="editor" :config="editorConfig"
							:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 80%;" />
					</div>
				</el-form-item>
				<div class="row-me row-center flex-wrap">
					<el-form-item label="广告推广">
						<el-image v-if="form.adverImg" class="width100 height100 radius6 margin-right10" :src="form.adverImg"
							:preview-src-list="[form.adverImg]"></el-image>
						<el-button type="text" @click="clickImg(2)">点击图片库</el-button>
					</el-form-item>
					<el-form-item label="跳转到">
						<el-select placeholder="请选择" v-model="form.linkTo">
							<el-option v-for="(item,index) in categoryList" :key="index" :label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="商品" v-if="form.linkTo==7">
						<el-select placeholder="请选择" v-model="form.objectId">
							<el-option v-for="(item,index) in productData" :key="index" :label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="机构" v-else-if="form.linkTo==9">
						<el-select placeholder="请选择" v-model="form.objectId">
							<el-option v-for="(item,index) in organData" :key="index" :label="item.organName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</div>
				<el-form-item label="选择试卷" prop="examId">
					<el-select v-model="form.examId" placeholder="请选择试卷" class="width260" filterable>
						<el-option v-for="item in examList" :key="item.id" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="试卷文件">
					<div class="row-me flex-wrap">
						<el-radio-group v-model="form.examStatus" class="margin-right20 margin-top10">
							<el-radio :label="0">开放下载</el-radio>
							<el-radio :label="1">文件上传</el-radio>
						</el-radio-group>
						<singleUploadLocal v-if="form.examStatus==1" message="支持扩展名: .raz .zip .doc .docx .pdf .jpg"
							@input="getwordData" :value="wordFileList">
						</singleUploadLocal>
					</div>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="mockExamVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleMockExamSave">确定</el-button>
			</span>
		</el-dialog>

		<!-- 授权用户 -->
		<el-dialog title="用户列表" :visible.sync="userVisible" width="60%">
			<authorizedUsers ref="authorizedUsers"></authorizedUsers>
		</el-dialog>

		<!-- 详情 -->
		<el-dialog title="详情" :visible.sync="detailVisible" width="70%">
			<questionsPageDetail ref="questionsPageDetail"></questionsPageDetail>
		</el-dialog>

		<!-- 题库管理后台新建试题 -->
		<el-dialog title="新建试题" :visible.sync="questionVisible" width="60%">
			<questionBank page="famousQuestion" type="1" @handleExamOk="handleExamOk"></questionBank>
		</el-dialog>

		<!-- 名试题库从题库系统添加/题库管理的历年真题添加试卷 -->
		<famousQuestion ref="famousQuestion" @handleOk="getData"></famousQuestion>

		<imgLibrary ref="imgLibrary" @handleImgOk="handleImgOk"></imgLibrary>

	</div>
</template>

<script>
	import QRCode from 'qrcodejs2';
	import famousQuestion from "@/components/famousQuestion"
	import authorizedUsers from "@/components/authorizedUsers"
	import questionsPageDetail from "@/components/questionsPageDetail"
	import imgLibrary from "@/components/imgLibrary"
	import singleUploadLocal from "@/components/Upload/singleUploadLocal"
	import questionBank from "@/components/questionBank"
	export default {
		props: ['page'], //page:famousQuestion 名师题库 page:historicalQuestion 历年真题 page:modelMatch 模考大赛
		components: {
			famousQuestion,
			authorizedUsers,
			questionsPageDetail,
			imgLibrary,
			singleUploadLocal,
			questionBank
		},
		data() {
			let that = this
			return {
				query: {
					pageNumber: 1,
					pageSize: 30
				},
				pageTotal: 0,
				tableData: [],
				multipleSelection: [],
				areaData: [],
				props: {
					emitPath: false,
					value: 'id',
					label: 'name',
					checkStrictly: true,
				},
				modelProps: {
					value: 'id',
					label: 'name',
					checkStrictly: true,
				},
				userVisible: false,
				detailVisible: false,
				qrcodeVisible: false,
				historyVisible: false,
				historyQuery: {
					pageNumber: 1,
					pageSize: 30
				},
				historyPageTotal: 0,
				historyTableData: [],
				multipleHistorySelection: [],
				formCopy: {},
				modelVisible: false,
				modelQuery: {
					pageNumber: 1,
					pageSize: 30
				},
				modelTableData: [],
				modelPageTotal: 0,
				modelAddVisible: false,
				modelForm: {
					configStatus: 0
				},
				modelRules: {
					labelName: {
						required: true,
						message: '请选择模考大赛标签',
						trigger: 'change'
					},
					mockId: {
						required: true,
						message: '请选择试卷',
						trigger: 'change'
					},
					configStatus: {
						required: true,
						message: '请选择状态',
						trigger: 'change'
					}
				},
				tagList: [],
				examList: [],
				configDate: [],
				form: {
					examStatus: 0
				},
				mockExamVisible: false,
				modelList: [],
				mockExamRules: {
					mockName: {
						required: true,
						message: '请输入大赛名称',
						trigger: 'blur'
					},
					mockComment: {
						required: true,
						message: '请输入大赛说明',
						trigger: 'blur'
					},
					examId: {
						required: true,
						message: '请选择试卷',
						trigger: 'change'
					},
					area: {
						required: true,
						message: '请选择地区',
						trigger: 'change'
					},
					examStart: {
						required: true,
						message: '请选择考试时间',
						trigger: 'change'
					},
					applyStart: {
						required: true,
						message: '请选择报名时间',
						trigger: 'change'
					}
				},
				examDate: [],
				applyDate: [],
				categoryList: [{
						id: 0,
						name: '不跳转'
					}, {
						id: 7,
						name: '跳转商品'
					},
					{
						id: 9,
						name: '跳转机构'
					}
				],
				wordFileList: [],
				roleType: '',
				questionVisible: false,
				isDetail: false,
				typeVisible: false,
				typeTableData: [],
				typeQuery: {
					pageNumber: 1,
					pageSize: 10
				},
				pageTypeTotal: 0,
				editorConfig: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgIndex = 1
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				imgIndex: 0,
				productData: [],
				organData: []
			}
		},
		filters: {
			testPaperStatus(value) {
				if (!value) return '待发布';
				else if (value == 1) return '待审核';
				else if (value == 2) return '已通过';
				else if (value == 3) return '未通过';
			},
			testStatus(value) {
				if (!value) return '待开始';
				else if (value == 1) return '报名中';
				else if (value == 2) return '报名结束';
				else if (value == 3) return '考试中';
				else if (value == 4) return '已结束';
			}
		},
		mounted() {
			this.roleType = localStorage.getItem('roleType')
			this.getAllArea()
			this.getData()
			if (this.page == 'historicalQuestion') {
				if (this.roleType == 3) {
					this.getTypeData()
				} else {
					this.getHistoryData()
				}
			}
			if (this.page == 'modelMatch') {
				this.getModelData()
				this.getTagList()
				this.getExamData()
				this.getConfigData()
				this.getProduceData()
				this.getOrganData()
			}
		},
		methods: {
			//获取商品下拉
			async getProduceData() {
				const res = await this.$get('/admin/mall/pageProduct', {
					pageNumber: 1,
					pageSize: 9999
				})
				if (res.code == 1000) {
					this.productData = res.data.list
				}
			},
			//获取商品下拉
			async getOrganData() {
				const res = await this.$postForm('/admin/messages/organAll', {
					pageNumber: 1,
					pageSize: 9999
				})
				if (res.code == 1000) {
					this.organData = res.data.list
				}
			},
			//分类分页
			handlePageTypeChange(val) {
				this.typeQuery.pageNumber = val
				this.getTypeData();
			},
			handleSizeTypeChange(val) {
				this.typeQuery.pageSize = val
				this.getTypeData();
			},
			//获取分类数据
			async getTypeData() {
				const res = await this.$postForm('/admin/examPaper/exampaperTypeAll', this.typeQuery)
				if (res.code == 1000) {
					this.typeTableData = res.data.list
					this.pageTypeTotal = res.data.totalRow
				}
			},
			// 新增编辑分类
			handleTypeAdd(row) {
				let params = {}
				let url;
				if (row.id) {
					params = {
						id: row.id,
						name: row.name
					}
					url = '/admin/examPaper/exampaperTypeUpdate'
				} else {
					params = {
						name: this.typeQuery.name
					}
					url = '/admin/examPaper/exampaperTypeAdd'
				}
				this.$post(url, params).then(res => {
					if (res.code == 1000) {
						this.$message.success('新增成功')
						this.getTypeData()
						this.typeQuery.name = ''
						row.isEdit = false
					}
				})
			},
			//删除分类
			async handleTypeDel(id) {
				const res = await this.$postForm('/admin/examPaper/exampaperTypeDeleted', {
					id
				})
				if (res.code == 1000) {
					this.$message.success('删除成功')
					this.getTypeData()
				}
			},
			handleExamOk() {
				this.questionVisible = false
				this.getData()
			},
			//获取试卷文件
			getwordData(data) {
				if (data && data.length != 0) {
					this.form.examWord = data[data.length - 1]
				}
			},
			//点击图片库
			clickImg(index) {
				this.imgIndex = index
				this.$refs.imgLibrary.show()
			},
			//获取选中的图片
			handleImgOk(data) {
				if (this.imgIndex == 1) {
					this.form.mockComment = this.form.mockComment + `<img src='${data}'>`
				} else {
					this.$set(this.form, 'adverImg', data)
				}
			},
			//新建编辑模考
			handleMockExamSave() {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.form.labelName = this.form.labelName ? this.form.labelName.toString() : ''
						this.form.isAdd = this.form.isAdd ? 1 : 0
						let url = '/admin/mocks/mockAdd'
						if (this.form.id) {
							url = '/admin/mocks/mockUpdate'
						}
						this.$post(url, this.form).then(res => {
							if (res.code == 1000) {
								this.$message.success('操作成功')
								this.getData()
								this.mockExamVisible = false
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			//删除模考大赛配置
			async handleConfigDel(id) {
				const res = await this.$post('/admin/mocks/mockConfigDeleteAll', [id])
				if (res.code == 1000) {
					this.$message.success('删除成功')
					this.getModelData()
				}
			},
			//新增编辑模考大赛配置
			handleConfigEdit(row) {
				if (row.id) {
					this.modelForm = JSON.parse(JSON.stringify(row))
					if (this.modelForm.configStatus == 2) {
						if (this.modelForm.configStart && this.modelForm.configEnd) {
							this.configDate = [this.modelForm.configStart, this.modelForm.configEnd]
						}
					}
					this.modelForm.area = []
					if (this.modelForm.province && this.modelForm.city) {
						let area = []
						if (this.modelForm.city == 0) {
							area = [this.modelForm.province].map(Number)
						} else {
							area = [this.modelForm.province, this.modelForm.city].map(Number)
						}
						this.$set(this.modelForm, 'area', area)
					}
					this.modelForm.labelName = this.modelForm.labelName ? this.modelForm.labelName.split(',') : []
				} else {
					this.modelForm = {}
					this.configDate = []
					this.modelForm.area = []
				}
				this.getConfigData()
				this.modelAddVisible = true
			},
			//配置时间变动
			configDateChange(val) {
				this.modelForm.configStart = ''
				this.modelForm.configEnd = ''
				if (val.length != 0) {
					this.modelForm.configStart = val[0]
					this.modelForm.configEnd = val[1]
				}
			},
			//考试时间变动
			mockDateChange(val) {
				this.form.examStart = ''
				this.form.examEnd = ''
				if (val.length != 0) {
					this.form.examStart = val[0]
					this.form.examEnd = val[1]
				}
			},
			//报名时间变动
			applyDateChange(val) {
				this.form.applyStart = ''
				this.form.applyEnd = ''
				if (val.length != 0) {
					this.form.applyStart = val[0]
					this.form.applyEnd = val[1]
				}
			},
			//获取试卷下拉
			async getExamData() {
				let params = {
					pageNumber: 1,
					pageSize: 99999,
				}
				const res = await this.$post('/admin/examPaper/pageExamPaper?' + this.$.getParamsString(params), {
					roleType: 2
				})
				if (res.code == 1000) {
					this.examList = res.data.list
				}
			},
			//获取标签下拉
			async getTagList() {
				const res = await this.$post('/admin/label/labelList')
				if (res.code == 1000) {
					this.tagList = res.data.list
				}
			},
			onModelChange(val) {
				this.modelForm.city = ''
				this.modelForm.province = ''
				if (val.length != 0) {
					this.modelForm.province = val[0]
					this.modelForm.city = val[1]
				}
			},
			onModelareaChange(val) {
				this.modelQuery.city = ''
				this.modelQuery.province = ''
				if (val.length != 0) {
					this.modelQuery.city = val[0]
					this.modelQuery.province = val[1]
				}
			},
			onMocklChange(val) {
				this.form.province = []
				this.form.city = []
				this.form.cityShow = []
				if (val.length != 0) {
					for (let item of val) {
						if (item[0]) {
							this.form.province.push(item[0])
						}
						if (item[1]) {
							this.form.city.push(item[1])
						}
					}
				}
				this.form.province = [...new Set(this.form.province)].toString()
				this.form.city = [...new Set(this.form.city)].toString()
				this.form.cityShow = JSON.stringify(val)
			},
			//新建编辑模考大赛
			handleModelSave() {
				this.$refs['modelForm'].validate(async (valid) => {
					if (valid) {
						this.modelForm.labelName = Array.isArray(this.modelForm.labelName) ? this.modelForm.labelName
							.toString() : this.modelForm.labelName
						let res = null
						if (this.modelForm.id) {
							res = await this.$post('/admin/mocks/mockConfigUpdate', this.modelForm)
						} else {
							res = await this.$post('/admin/mocks/mockConfigAdd', this.modelForm)
						}
						if (res.code == 1000) {
							this.$message.success('操作成功')
							this.getModelData()
							this.modelAddVisible = false
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			handleModelPageChange(val) {
				this.modelQuery.pageNumber = val
				this.getModelData()
			},
			//获取模考大赛配置列表
			async getModelData() {
				const res = await this.$postForm('/admin/mocks/mockConfigAll', this.modelQuery)
				if (res.code == 1000) {
					this.modelTableData = res.data.list
					this.modelPageTotal = res.data.totalRow
				}
			},
			//模考大赛配置搜索
			modelSearch() {
				this.modelQuery.pageNumber = 1
				this.getModelData()
			},
			// 复制
			copys() {
				let url = '/admin/examPaper/saveExamPaperCopy'
				if (this.page == 'modelMatch') {
					url = '/admin/mocks/mockShowSave'
				}
				this.$post(url, this.formCopy).then(res => {
					if (res.code == 1000) {
						this.$message({
							type: 'success',
							message: '复制成功!'
						});
						this.getData()
					}
				})
			},
			//复制
			updateItemCopy(row) {
				this.$confirm('确定要复制试卷吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.copys()
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消复制'
					});
				});
				if (this.page == 'modelMatch') {
					this.$postForm('/admin/mocks/mockShowFind', {
						id: row.id
					}).then(res => {
						if (res.code == 1000) {
							this.formCopy = res.data
						}
					})
				} else {
					this.$get('/admin/examPaper/getExamPaperById', {
						id: row.id
					}).then(res => {
						if (res.code == 1000) {
							this.formCopy = res.data
						}
					})
				}

			},
			//获取试卷
			async getHistoryData() {
				const res = await this.$post('/admin/examPaper/pageExamPaper?' + this.$.getParamsString(this.historyQuery), {
					roleType: 2,
					status: 2
				})
				if (res.code == 1000) {
					this.historyTableData = res.data.list
					this.historyPageTotal = res.data.totalRow
				}
			},
			handleHistoryPageChange(val) {
				this.historyQuery.pageNumber = val
				this.getHistoryData()
			},
			//搜索
			historySearch() {
				this.historyQuery.pageNumber = 1
				this.getHistoryData()
			},
			//重置
			historyRefresh() {
				this.historyQuery = {
					pageNumber: 1,
					pageSize: 30
				}
				this.getHistoryData()
			},
			// 历年真题从题库添加
			async handleHistorySave() {
				if (this.multipleHistorySelection.length == 0) return
				let ids = Array.from(this.multipleHistorySelection, ({
					id
				}) => id)
				const res = await this.$post('/admin/examPaper/organExampaperAdd', ids)
				if (res.code == 1000) {
					this.$message.success('添加成功')
					this.getData()
					this.historyVisible = false
				}
			},
			// 点击下载图片
			handleDownloadAppExamQrIMg(id) {
				// 这里是获取到的图片base64编码
				var name = this.$refs.appExamQrCodeUrl.name;
				var img = document.getElementById(id).getElementsByTagName('img')[0];
				const imgUrl = img.src;
				// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
				if (window.navigator.msSaveOrOpenBlob) {
					let bstr = atob(imgUrl.split(',')[1]);
					let n = bstr.length;
					let u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					let blob = new Blob([u8arr]);
					window.navigator.msSaveOrOpenBlob(blob, name + '.' + 'png');
				} else {
					// 这里就按照chrome等新版浏览器来处理
					let a = document.createElement('a');
					a.href = imgUrl;
					a.setAttribute('download', name + '.' + 'png');
					a.click();
				}
			},
			// 试卷APP二维码
			handleAppExamQrcode(row) {
				let type = "exam"
				if (this.page == 'famousQuestion') {
					type = "exam1"
				} else if (this.page == 'modelMatch') {
					type = "mock"
				}
				var vm = this;
				this.appExamQrcodeVisible = true;
				setTimeout(function() {
					vm.$refs.appExamQrCodeUrl.innerHTML = '';
					vm.$refs.appExamQrCodeUrl.name = row.id + "-" + row.name;
					var qrcode = new QRCode('code', {
						text: 'https://admin.shuatibang.com/h5/login.html?{"type":"' + type + '","id":"' + row.id +
							'","appid":"' + row.appid + '"}', // 需要转换为二维码的内容
						width: 150,
						height: 150,
						colorDark: '#000000',
						colorLight: '#ffffff',
						correctLevel: QRCode.CorrectLevel.H
					});
				}, 200);
			},
			// 试卷APP查看答案二维码
			handleAppExamAnswerQrcode(row) {
				let type = "examAnswer"
				let id = row.id
				let idName = 'id'
				let examType = 2
				let params = null
				if (this.page == 'famousQuestion') {
					examType = 1
				}
				if (this.page == 'modelMatch') {
					examType = 3
					idName = 'mockId'
					params = (',"id":"' + row.examId + '"') + (',"mockTitle":"' + row.mockName + '"')
				}
				var vm = this;
				this.appExamQrcodeVisible = true;
				setTimeout(function() {
					vm.$refs.appExamQrCodeUrl2.innerHTML = '';
					vm.$refs.appExamQrCodeUrl2.name = row.id + "-" + row.name;
					var qrcode = new QRCode('code2', {
						text: 'https://admin.shuatibang.com/h5/login.html?{"type":"' + type + '","examType":"' + examType +
							'","' + idName + '":"' + id +
							'","appid":"' + row.appid + '"' + (params ? params : '') + '}', // 需要转换为二维码的内容
						width: 150,
						height: 150,
						colorDark: '#000000',
						colorLight: '#ffffff',
						correctLevel: QRCode.CorrectLevel.H
					});
				}, 200);
			},
			// 点击查看弹框
			lookQrcode(row) {
				this.qrcodeVisible = true;
				this.handleAppExamQrcode(row)
				this.handleAppExamAnswerQrcode(row)
			},
			//详情
			handleDetail(row) {
				this.isDetail = true
				if (this.page == 'famousQuestion') {
					// this.$refs.famousQuestion.show(this.page, row)
					this.detailVisible = true
					setTimeout(() => {
						this.$refs.questionsPageDetail.show(row.id)
					})
				} else if (this.page == 'historicalQuestion') {
					if (this.roleType == 3) {
						this.$refs.famousQuestion.show(this.page, row, 1)
					} else {
						this.detailVisible = true
						setTimeout(() => {
							this.$refs.questionsPageDetail.show(row.id)
						})
					}
				} else if (this.page == 'modelMatch') {
					this.form = JSON.parse(JSON.stringify(row))
					this.form.isAdd = this.form.isAdd ? true : false
					this.form.labelName = this.form.labelName ? this.form.labelName.split(',') : this.form.labelName
					if (this.form.examStart && this.form.examEnd) {
						this.examDate = [this.form.examStart, this.form.examEnd]
					}
					if (this.form.applyStart && this.form.applyEnd) {
						this.applyDate = [this.form.applyStart, this.form.applyEnd]
					}
					this.form.area = this.form.cityShow ? JSON.parse(this.form.cityShow) : []
					if (this.form.examWord) {
						this.wordFileList = [{
							name: this.form.examWord,
							url: this.form.examWord
						}]
					}
					this.mockExamVisible = true
				}
			},
			//授权用户
			handleAddUser(row) {
				setTimeout(() => {
					this.$refs.authorizedUsers.show(row.id)
				})
				this.userVisible = true
			},
			//发布撤销
			releaseHandle(index, row, type) {
				this.$confirm('确定要' + (type == 2 ? '撤销' : '发布') + '试卷【' + (row.name || row.mockName) + '】吗？', '提示', {
					type: 'warning'
				}).then(() => {
					let url = '/admin/examPaper/releaseExamPager'
					let params = {
						id: row.id,
						status: type
					}
					if (this.page == 'modelMatch') {
						url = "/admin/mocks/mockUpdate"
						params = {
							id: row.id,
							mockStatus: type
						}
					}
					this.$post(url, params).then(res => {
						if (res.code == 1000) {
							this.$message.success((type == 2 ? '撤销' : '发布') + '成功');
							this.getData();
						}
					})
				});
			},
			//审核
			verifyHandle(command, row) {
				let url = '/admin/examPaper/releaseExamPager'
				if (this.page == 'modelMatch') {
					url = "/admin/mocks/mockUpdate"
				}
				this.$confirm('确定要' + (command == 2 ? '通过' : '拒绝') + '试卷【' + (row.name || row.mockName) + '】吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.$post(url, {
						id: row.id,
						status: command
					}).then(res => {
						if (res.code == 1000) {
							this.$message.success(command == 2 ? '已通过' : '已拒绝');
							this.getData();
						}
					})
				});
			},
			//删除
			handleDel(id) {
				if (this.page == 'modelMatch') {
					this.$post('/admin/mocks/mockDeleteAll', [id]).then(res => {
						if (res.code == 1000) {
							this.$message.success('删除成功')
							this.getData()
						}
					})
				} else {
					this.$post('/admin/examPaper/deleteExamPager', {
						id,
						type: this.query.type
					}).then(res => {
						if (res.code == 1000) {
							this.$message.success('删除成功')
							this.getData()
						}
					})
				}
			},
			//获取省市区树
			async getAllArea() {
				const res = await this.$get('/admin/area/getAllArea')
				if (res.code == 1000) {
					this.areaData = this.$.getTreeData(res.data)
					this.areaData.unshift({
						adcode: '0',
						name: '默认',
						parentId: 0,
						id: '0'
					})
				}
			},
			//批量删除
			handleBatchDel() {
				this.$confirm('确定要批量删除已选中试题吗？', '提示', {
					type: 'warning'
				}).then(() => {
					if (this.multipleSelection.length == 0) return
					let ids = Array.from(this.multipleSelection, ({
						id
					}) => id)
					let url = '/admin/examPaper/exampaperDeleteAll'
					if (this.page == 'modelMatch') {
						url = '/admin/mocks/mockDeleteAll'
					}
					this.$post(url, ids).then(res => {
						if (res.code == 1000) {
							this.$message.success('批量删除成功')
							this.getData()
						}
					})
				}).catch(() => {})
			},
			//添加试题
			handleAddQuestion() {
				this.questionVisible = true
			},
			//一键更新
			async clickRenew() {
				const res = await this.$postForm('/admin/examPaper/examPaperSyncAll')
				if (res.code == 1000) {
					this.$message.success('一键更新成功')
					this.getData()
				}
			},
			//从题库添加
			handleAdd(row) {
				this.isDetail = false
				if (this.page == 'modelMatch') {
					if (row.id) {
						this.form = JSON.parse(JSON.stringify(row))
						this.form.isAdd = this.form.isAdd ? true : false
						this.form.labelName = this.form.labelName ? this.form.labelName.split(',') : this.form.labelName
						if (this.form.examStart && this.form.examEnd) {
							this.examDate = [this.form.examStart, this.form.examEnd]
						}
						if (this.form.applyStart && this.form.applyEnd) {
							this.applyDate = [this.form.applyStart, this.form.applyEnd]
						}
						if (this.form.province && this.form.city) {
							if (this.form.city == 0) {
								this.form.area = [this.form.province].map(Number)
							} else {
								this.form.area = [this.form.province, this.form.city].map(Number)
							}
						}
						if (this.form.examWord) {
							this.wordFileList = [{
								name: this.form.examWord,
								url: this.form.examWord
							}]
						}
					} else {
						this.form = {
							examStatus: 0
						}
						this.examDate = []
						this.applyDate = []
						this.form.area = []
						this.wordFileList = []
						this.isDetail = false
					}
					this.mockExamVisible = true
				} else {
					this.$refs.famousQuestion.show(this.page, row)
				}

			},
			//分页
			handlePageChange(val) {
				this.query.pageNumber = val
				this.getData();
			},
			handleSizeChange(val) {
				this.query.pageSize = val
				this.getData();
			},
			//多选操作
			handleSelectionChange(val) {
				this.multipleSelection = val
			},
			//历年真题多选操作
			handleHistorySelectionChange(val) {
				this.multipleHistorySelection = val
			},
			//获取列表数据
			getData() {
				if (this.page == 'modelMatch') {
					this.$postForm(
						`/admin/mocks/mockAll?pageNumber=${this.query.pageNumber}&pageSize=${this.query.pageSize}`, this
						.query).then(res => {
						if (res.code == 1000) {
							this.tableData = res.data.list
							this.pageTotal = res.data.totalRow
						}
					})
				} else {
					if (this.page == 'historicalQuestion') {
						this.query.type = 0
					} else if (this.page == 'famousQuestion') {
						this.query.type = 2
					}
					if (this.roleType == 3) {
						this.query.roleType = 2
					} else {
						this.query.roleType = 1
					}
					this.$post(
						`/admin/examPaper/pageExamPaper?pageNumber=${this.query.pageNumber}&pageSize=${this.query.pageSize}`,
						this.query).then(res => {
						if (res.code == 1000) {
							this.tableData = res.data.list
							this.pageTotal = res.data.totalRow
						}
					})
				}

			},
			//获取模考大赛配置里的试卷下拉
			async getConfigData() {
				let params = {
					pageNumber: 1,
					pageSize: 99999
				}
				const res = await this.$post('/admin/mocks/mockAll?' + this.$.getParamsString(params), {
					pageNumber: 1,
					pageSize: 99999
				})
				if (res.code == 1000) {
					this.modelList = res.data.list
				}
			},
			//搜索
			handleSearch() {
				this.query.pageNumber = 1
				if (this.page == 'modelMatch') {
					this.query.mockName = this.query.name || ''
					this.query.mockStatus = this.query.status || ''
				}
				this.getData();
			},
			//查询
			handleRefresh() {
				this.query = {
					pageNumber: 1,
					pageSize: 30
				}
				this.getData();
			},
			//排序
			clickSort(type) {
				this.query.sortType = type
				this.handleSearch()
			},
		}
	}
</script>

<style scoped>
	/deep/ .el-table__header {
		/* // 使表格兼容safari，不错位,表头宽度较小 */
		width: 100%;
		table-layout: fixed !important;
	}

	/deep/ .el-table__body {
		width: 100%;
		/* // 使表格兼容safari，不错位 */
		table-layout: fixed !important;
	}
</style>